import os, sys, string, JobExecution, thread;
from ResourceManager import *;
"""
It will import Configuration from ResourceManager
"""
class CloudManager:
    
    def isBusy(self, serverTuple):
        cmd = "ps aux|grep " + Configuration.userName + "|grep python JobExecution.py"
        cmd = "ssh -i "+ Configuration.sshKey + " " + Configuration.userName + "@"+ serverTuple[0] + " '" + cmd + "'";
        file = os.popen(cmd)
        lines = file.readlines()
        if(len(lines)>0):
            return True;
        return False;
    
    def runInCloud(self, expId, expName, maxYear, factor, serverTuple):
        ft = True;
        print "-------------------------------------------------"
        hostname = Configuration.getHostName();
    #    for serverTuple in serverNames:
    #        if(isBusy(serverTuple)):
    #            continue;
        servername = Configuration.userName+"@" + serverTuple[0]
        cmd = "cd "+ Configuration.remoteScriptDirectory + "; python JobExecution.py " + "%d"%expId + " " + expName + " " + "%d"%maxYear + " " + "%d"%factor + " NONULL"
        if ft == True:
            cmd = cmd + " " + "ft"
        cmd = "ssh -i " + Configuration.sshKey + " " + servername + " '" + cmd + "&'&"
        print cmd
        os.system(cmd)
        print "-----------------------------------------------------"
        return True
    
    isInitMachines = False;
    """Provision machines"""
    def provision(self, type="m1.small"):
        isInitMachines = True;
        return "servername"
    """ Shut down computers """
    def release(self, servername):
        return "servername"
    
#    def getFreeMachines(self, type):
#        machines = [];
#        for serverAddress in serverNames:
#            if(self.isBusy(serverAddress)):
#                continue;
#            machines.append(serverAddress);
#        return machines
        """We can play some resource scheduling techniques such as dynamic allocate more machines or wait or prediction"""
        """This function will be added soon"""
    
    def getServer(self, serverType):
        machineList = self.machines[serverType];
        for serverTuple in machineList:
            if(self.isBusy(serverTuple)):
                continue;
            return serverTuple;
        return None;
    
    def __init__(self):
        self.serverNames = ["fs3.das4.tudelft.nl", "fs0.das4.cs.vu.nl"];
        self.machines = {};
        #types: such m1.small, m1.large etc
        types = [];
        filename = os.path.join("..", "conf","cloud.conf")
        file = open(filename)
        lines = file.readlines();
        l = []
        for line in lines:
            if line.find("#") < 0 and len(line.strip())>0:
                l.append(line);
        lines = l;
        for i in range(0, len(lines)):
            line = lines[i];
#            print line
            if line.find("#") < 0 and len(line.strip())>0:
                tup = string.split(line);
                if(tup[0] == "TYPE"):
                    if(tup[1] in types):
                        sys.stderr.write("duplicate list of the same type " + tup[1])
                    else:
                        types.append(tup[1]);
                        currentType = tup[1];
                        line = lines[i + 1];
                        tup = string.split(line);
                        if(tup[0] == "NUMBER"):
                            numberOfMachine = string.atoi(tup[1]);
                            machis = [];
                            for j in range(0, numberOfMachine):
                                line = lines[i + j + 2];
                                tup = string.split(line, ",");
                                tup[0] = tup[0].strip(); tup[1] = tup[1].strip();
                                machis.append(tup);
                            i = i + j + 2;
                            self.machines[currentType] = machis;
#        for type in self.machines.keys():
#            machis = self.machines[type];
#            for tup in machis:
#                print tup;
                
    def run(self):
        global expNames
        global experiments
        print expNames
        insertExpIntoExperiments()
        print experiments
        thread.start_new_thread(listenNewJobs, ())
        while True:
            print "sleeping, ", experiments
            if len(experiments) ==0:
                time.sleep(5)
            else:
                exp = experiments.pop(0)
                expName = exp[0]
                serverType = exp[1:2][0]
                numOfInstance = string.atoi(exp[2:3][0])
                factors = exp[3:]
                Configuration.increaseId()
                expId = Configuration.getId(); 
                maxYear = Configuration.getMaxYear(expName)
                print "testAll", factors
                for factor in factors:
                    if serverType == "anyType": # not tested yet, there may be bugs
                        print "anyTYPE is ok "
                        servername = self.getServer(serverType)
                        if(servername == None):
                            continue;
                        print "found a server " + servername
                        thread.start_new_thread(self.runInCloud,(expId, expName, factor, servername, maxYear, numOfInstance))
                    else :
                        print "The server required: " + serverType
                        while True:
                            servername = self.getServer(serverType);
                            if(servername != None):
                                break;
                            time.sleep(10);
#                                                        (self, expId, expName, maxYear, factor, serverTuple)
                        thread.start_new_thread(self.runInCloud,(expId, expName, maxYear, factor, servername))
                    time.sleep(15)
            time.sleep(1)
        
if __name__ == "__main__":
    cloudManager = CloudManager();
    cloudManager.run();
    time.sleep(5);
#    SubmitNewExps.submitExps("1a1", [1], 1, "m1.small", "127.0.0.1")
#    m.run();